import inspect
import os
import sys
import time
import static.globals as sg

import datetime

from cache.redis_util import getConnection
from dbse.mysql.db_entity_stock_ths_gn_current_info import StockCurrentThsGnInfo
from dbse.mysql.db_mysql_insert import addStockThsGnCurrentInfo, getDataBase


def test_split():
    dataStr = "http://q.10jqka.com.cn/gn/detail/code/301455/"
    items = dataStr.split("/")
    print(items)
    print(len(items)-2)
    print(items[len(items)-2])

def test_date():
    today = datetime.date.today()
    print(today)
    print(today.strftime("%Y-%m-%d"))

def isNone():
    browser = None;
    print(browser == None)
def isNone2():
    try:
        browser = 1/0
    except Exception as e:
        print('error')
        print(browser == None)

# 获取调用者信息
def get_caller_info():
    stack = inspect.stack()

    # 调用者帧信息（索引1是调用者，索引0是当前函数）
    caller_frame = stack[1][0]

    # 获取调用者信息
    caller_info = {
        'function': stack[1][3],  # 函数名
        'filename': stack[1][1],  # 文件名
        'lineno': stack[1][2],    # 行号
        'locals': caller_frame.f_locals,  # 局部变量
        'globals': caller_frame.f_globals  # 全局变量
    }
    print(caller_info)
    return caller_info

def function_c():
    print("文件C中的函数被调用")

    # 分析调用栈
    stack = inspect.stack()

    # 检查调用链中是否包含文件A
    call_chain = []
    for frame_info in stack:
        filename = frame_info.filename
        function_name = frame_info.function

        # 获取基础文件名（不含路径）
        base_filename = os.path.basename(filename)
        call_chain.append((base_filename, function_name))

        # 检查是否来自文件A
        if base_filename == "file_a.py":
            print("✅ 检测到调用链来自 file_a.py")
            print_call_chain(stack)
            return "调用来自文件A"

    print("❌ 调用链中未找到 file_a.py")
    print_call_chain(stack)
    return "调用不是来自文件A"

def print_call_chain(stack):
    """打印完整的调用链"""
    print("\n📋 完整调用链:")
    for i, frame_info in enumerate(stack):
        filename = os.path.basename(frame_info.filename)
        print(f"{i}: {filename} -> {frame_info.function} (行号: {frame_info.lineno})")

def testExit():
    error = 0
    while True:
        print(f"====continue,current error is:{error}")
        time.sleep(2)
        error = error + 1
        if(error > 5):
            print("============error is larger than 5 exit=============")
            sys.exit()

def sanyuan():
    x = 6
    result = "大于5" if x > 5 else "小于等于5"
    print(result)

def test123():
    proxy_data = {'proxy_address':f'123'}
    print(f"===============使用代理:{proxy_data.get('proxy_address')}")

def testGlobal1():
    print(sg.batch)
    sg.batch = 2
    print(sg.batch)

def testGlobal2():
    while True:
        print(sg.batch)
        time.sleep(5)

'''
修改sg.batch  观察 testGlocal2 的sg.batch 是否被污染
结论： 两个进程之间global 独立
'''
def testGlobal3():
    while True:
        print(sg.batch)
        sg.batch = sg.batch +1
        time.sleep(5)

def testTemp():
    redis = getConnection('prod')
    count = redis.incr("stock:count:gn:current")
    count = count % 389 +1
    print(count)
    print(f'stock:gn:{count}')
    url = redis.hget(f'stock:gn:{count}',"url").decode('utf-8')
    gnCode = redis.hget(f'stock:gn:{count}',"gn_code").decode('utf-8')

def testInsertGnCurrent():
    db = getDataBase('prod')
    add_sql = 'INSERT INTO stock_ths_gn_current_info (gn_code,gn_name,price_begin,price_yesterday,price_end,price_max,price_min,price_increase_rate,rank,up_num,down_num,fund_input,amount,trunover,sta_datetime,price_current) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
    # 保存数据
    entity = StockCurrentThsGnInfo('002648',
                                   None,                                            #gn_name
                                   None,                                  #price_begin
                                   None,                                  #price_yesterday
                                   None,                                            #price_end
                                   None,                                  #price_max
                                   None,                                  #price_min
                                   None,                                            #price_increase_rate
                                   None,                    #rank
                                   None,                 #up_num
                                   None,                 #down_num
                                   None,                                  #fund_input
                                   None,                                  #amount
                                   None,                                  #trunover
                                   None,                                   #sta_datetime
                                   None                                   # price_current
                                   )
    # entity = StockCurrentThsGnInfo('002648',
    #                                gn_name,                                            #gn_name
    #                                result[0].text,                                  #price_begin
    #                                result[1].text,                                  #price_yesterday
    #                                None,                                            #price_end
    #                                result[3].text,                                  #price_max
    #                                result[2].text,                                  #price_min
    #                                None,                                            #price_increase_rate
    #                                result[6].text.split("/")[0],                    #rank
    #                                result[7].getchildren()[0].text,                 #up_num
    #                                result[7].getchildren()[1].text,                 #down_num
    #                                result[8].text,                                  #fund_input
    #                                result[9].text,                                  #amount
    #                                result[4].text,                                  #trunover
    #                                getDateTime(),                                   #sta_datetime
    #                                price_current                                    # price_current
    #                                )
    addStockThsGnCurrentInfo(db,add_sql,entity)

testInsertGnCurrent()